//
//  baseHttpClient.m
//  baseVC
//
//  Created by 陶磊 on 2019/12/16.
//  Copyright © 2019 QHT. All rights reserved.
//

#import "baseHttpClient.h"
#import "baseURLConfig.h"
#import "baseErrorCodeHandler.h"
#import "AFNetworkActivityIndicatorManager.h"

#define NetworkingFailCode 100002

// 成功code
static const NSInteger successCode = 200;

// 超时时间
static const NSInteger timeoutNumber = 8;

@interface baseHttpClient ()

@end

@implementation baseHttpClient

+ (baseHttpClient*)getInstance
{
    static baseHttpClient *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[baseHttpClient alloc] init];
    });
    return _sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        if (![self setup]) return nil;
    }
    return self;
}

+ (baseHttpClient *)httpClient
{
    return [self getInstance];
//    return [[self alloc] init];
}

- (BOOL)setup
{
//    NSString *baseURL = [[NSUserDefaults standardUserDefaults] objectForKey:@"baseURL"];
//    NSString *port = [[NSUserDefaults standardUserDefaults] objectForKey:@"port"];
//
//    if (!baseURL.length) {
//        [ZHUToast makeOnTheWindow:@"请先设置服务器地址"];
//        [ZHUToast hideActivityOnTheWindow];
//        return NO;
//    }
    
    _AFNHttpManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", baseURL]]];
    if (!_AFNHttpManager) {
        return NO;
    }
    
    
    _AFNHttpManager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    //超时时间15秒
    _AFNHttpManager.requestSerializer.timeoutInterval = timeoutNumber;
    
    //response
    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
    //将null转换为nil
    serializer.removesKeysWithNullValues = YES;
    _AFNHttpManager.responseSerializer = serializer;
    
    
    //内容类型
    _AFNHttpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html", nil];
    [_AFNHttpManager.requestSerializer setValue:[USERDEFAULT valueForKey:@"token"] forHTTPHeaderField:@"Authori-zation"];

//      [_AFNHttpManager.requestSerializer setValue:@"application/json;charset=utf-8"forHTTPHeaderField:@"Content-Type"];
    
    //在AFNetworking请求的时候，自动加上系统指示器..
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
//    https设置
//    [self setHttpsCert];

    
    return YES;
}

- (void)setHttpsCert{
    
    //https设置
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"pandian" ofType:@"cer"];//证书的路径
    
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    if (certData) {
        NSMutableSet *certSet = [NSMutableSet set];
        [certSet addObject:certData];
        AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:certSet];
        policy.allowInvalidCertificates = YES;//允许失效的证书 NO
        //        policy.validatesDomainName = NO;//是否验证域名有效性
        _AFNHttpManager.securityPolicy = policy;
    }
    
//    //https设置
//    //服务器端配置的包含公钥的证书分发到客户端,验证证书
//    NSString *certkey = [[CLCWCachDataUtil getInstance] getChipContent:@"httpsCA"] ;//从碎片获取证书秘钥
//    //去掉头尾和回车符
//    NSString *certkeyString = [CLCWCommonMethod getPublicKeyCertString:certkey];
//    //base64转换成nsdata类型
//    NSData *RootCertData = [[NSData alloc]initWithBase64EncodedString:certkeyString options:NSDataBase64DecodingIgnoreUnknownCharacters];
//    NSMutableSet *certSet = [NSMutableSet set];
//    if (RootCertData)
//    {
//        [certSet addObject:RootCertData];
//        AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:certSet];
//        policy.allowInvalidCertificates = NO;//允许失效的证书 NO
//        _AFNHttpManager.securityPolicy = policy;
//    }
//
//    [CLCWCommonMethod cookieSetupWithAuditing];

}

//+ (NSString *)addPrefix:(NSString *)URLString
//{
//    return [NSString stringWithFormat:@"%@%@", basePrefixURL, URLString];
//}

//POST
- (NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(id)parameters
                   isNeedlogin:(BOOL)isNeedlogin
                       success:(requestBlock)success
                       failure:(requestBlock)failure
{
    
    NSString *totalURLString = [NSString stringWithFormat:@"%@%@",baseURL,URLString];
//    if (![URLString hasPrefix:@"http://"] && ![URLString hasPrefix:@"https://"]) {
//        totalURLString = [CLCWHttpClient addPrefix:URLString];
//    }
    
    //先判断登录状态
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    
//    if (isNeedlogin)
//    {
        parDic = [baseCommonMethod commonParameters];//带认证参数
//    }
    
    [parDic addEntriesFromDictionary:parameters];//合并参数
    
    _AFNHttpManager.requestSerializer.timeoutInterval = timeoutNumber;
    
//    _AFNHttpManager = [AFHTTPSessionManager manager];
//    _AFNHttpManager.requestSerializer = [AFJSONRequestSerializer serializer];
//    _AFNHttpManager.responseSerializer = [AFJSONResponseSerializer serializer];
//    [_AFNHttpManager.requestSerializer setValue:[USERDEFAULT valueForKey:@"token"] forHTTPHeaderField:@"Authori-zation"];
    
    // 如果有设置超时时间参数,修改超时时间
    if (parDic[@"AFNTimeoutInterval"] && [parDic[@"AFNTimeoutInterval"] integerValue]) {
        _AFNHttpManager.requestSerializer.timeoutInterval = [parDic[@"AFNTimeoutInterval"] integerValue];
        [parDic removeObjectForKey:@"AFNTimeoutInterval"];
    }
    //请求数据
    return [_AFNHttpManager POST:totalURLString parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject)
        {
            //有数据返回
            NSInteger code = [responseObject[@"status"] integerValue];
            id data = responseObject;
            NSString *msgStr = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            
            if (code == successCode)
            {
                if ([data isKindOfClass:[NSNull class]]) {
                    data = nil;
                }
                //有结果返回
                success ? success(data, code, msgStr) : nil;
            }
            else
            {
                //无结果返回,code == 300...
                //统一处理errorCode
                baseErrorCodeHandler *errorHandler = [[baseErrorCodeHandler alloc] init];
                [errorHandler handlerErrorCode:code msg:msgStr];
                
                failure ? failure(data, code, msgStr) : nil;
            }
        }
        else
        {
            //无数据返回
            failure ? failure(nil, -2, @"网络请求失败，-2") : nil;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //网络请求失败
            if (error.code == NSURLErrorCancelled | error.code == NSURLErrorSecureConnectionFailed | error.code == NSURLErrorServerCertificateHasBadDate | error.code == NSURLErrorServerCertificateUntrusted | error.code == NSURLErrorServerCertificateNotYetValid)
            {//https证书异常
//                failure(nil, -999, @"网络已断开，请检查网络设置");
//                if (![URLString isEqualToString:CLCWCommonGetConfigUpdateURL]) {
//                    [CLCWHttpClient updateChipConfig];
//                }
            } else{
//                [XHToast showBottomWithText:@"网络已断开，请检查网络设置"];
                failure ? failure(nil, NetworkingFailCode, @"网络已断开，请检查网络设置") : nil;
            }
    }];
}

//GET
- (NSURLSessionDataTask *)GET:(NSString *)URLString
                   parameters:(id)parameters
                      success:(requestBlock)success
                      failure:(requestBlock)failure
{
    
//    _AFNHttpManager = [AFHTTPSessionManager manager];
//    _AFNHttpManager.requestSerializer = [AFJSONRequestSerializer serializer];
//    _AFNHttpManager.responseSerializer = [AFJSONResponseSerializer serializer];
    [_AFNHttpManager.requestSerializer setValue:[USERDEFAULT valueForKey:@"token"] forHTTPHeaderField:@"token"];
    
    return [_AFNHttpManager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject)
        {
            //有数据返回
            NSInteger code = [responseObject[@"code"] integerValue];
            id data = responseObject;
            NSString *msgStr = [NSString stringWithFormat:@"%@", responseObject[@"msg"]];
            
            if (code == 1)
            {
                //有结果返回
                success ? success(data, code, msgStr) : nil;
            }
            else
            {
                //无结果返回
                //统一处理errorCode
                baseErrorCodeHandler *errorHandler = [[baseErrorCodeHandler alloc] init];
                [errorHandler handlerErrorCode:code msg:msgStr];
                
                failure ? failure(data, code, msgStr) : nil;
            }
        }
        else
        {
            //无数据返回
            failure ? failure(nil, -2, @"网络请求失败，-2") : nil;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //网络请求失败
        if (error) {
            if (error.code != NSURLErrorCancelled) {
                failure ? failure(nil, NetworkingFailCode, @"网络请求失败") : nil;
            } else {
                //请求取消，不做任何反应
            }
        } else {
            failure ? failure(nil, NetworkingFailCode, @"网络请求失败") : nil;
        }
    }];
}

- (NSURLSessionDownloadTask *)DownloadFile:(NSString *)URLString
                               success:(requestBlock)success
                               failure:(requestBlock)failure
{
    //1.创建会话管理者
    NSURL *url = [NSURL URLWithString:URLString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //2.下载文件
    /*
     第一个参数:请求对象
     第二个参数:progress 进度回调 downloadProgress
     第三个参数:destination 回调(目标位置)
     有返回值
     targetPath:临时文件路径
     response:响应头信息
     第四个参数:completionHandler 下载完成之后的回调
     filePath:最终的文件路径
     */
    NSURLSessionDownloadTask *downloadTask= [_AFNHttpManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //监听下载进度
        //completedUnitCount 已经下载的数据大小
        //totalUnitCount     文件数据的中大小
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        success(filePath, 200, @"download ok");
        
    }];
    [downloadTask resume];
    return downloadTask;
}

/** 便利构造器 */
+ (NSURLSessionDataTask *) requestPOST:(NSString *)URLString
                            parameters:(id)parameters
                               isNeedlogin:(BOOL)isNeedlogin
                               success:(requestBlock)success
                               failure:(requestBlock)failure {
    return [[self httpClient] POST:URLString parameters:parameters isNeedlogin:isNeedlogin success:success failure:failure];
}

/** 便利构造器 */
+ (NSURLSessionDataTask *) requestGet:(NSString *)URLString
                           parameters:(id)parameters
                              success:(requestBlock)success
                              failure:(requestBlock)failure {
    return [[self httpClient] GET:URLString parameters:parameters success:success failure:failure];
}

/** 便利构造器 */
+ (NSURLSessionDownloadTask *)DownloadFile:(NSString *)URLString
                               success:(requestBlock)success
                               failure:(requestBlock)failure{
    return [[self getInstance] DownloadFile:URLString success:success failure:failure];
}

#pragma mark -- 这是盘点项目
/** 便利构造器 */
+ (NSURLSessionDataTask *)downloadFile:(NSString *)URLString
                               success:(requestBlock)success
                               failure:(requestBlock)failure{
    return [[self httpClient] downloadFile:URLString success:success failure:failure];
}

- (NSURLSessionDownloadTask *)downloadFile:(NSString *)URLString
                                   success:(requestBlock)success
                                   failure:(requestBlock)failure
{
    // baseURL
//    NSString *baseURL = [USERDEFAULT objectForKey:ZHUBaseIP];
//    NSString *port = [USERDEFAULT objectForKey:ZHUPort];
//    NSString *baseURL = @"115.159.156.197";
//    NSString *port = @"8443";
    NSString *baseURL = [[NSUserDefaults standardUserDefaults] objectForKey:@"baseURL"];
    NSString *port = [[NSUserDefaults standardUserDefaults] objectForKey:@"port"];
    
    if (!baseURL.length) {
        return nil;
    }
//    clc
    NSString *fullURLStr = [NSString stringWithFormat:@"%@%@:%@/%@",baseURL,baseURL, port, URLString];
    //1.创建会话管理者
    NSURL *url = [NSURL URLWithString:fullURLStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //2.下载文件
    /*
     第一个参数:请求对象
     第二个参数:progress 进度回调 downloadProgress
     第三个参数:destination 回调(目标位置)
     有返回值
     targetPath:临时文件路径
     response:响应头信息
     第四个参数:completionHandler 下载完成之后的回调
     filePath:最终的文件路径
     */
    NSURLSessionDownloadTask *downloadTask= [_AFNHttpManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //监听下载进度
        //completedUnitCount 已经下载的数据大小
        //totalUnitCount     文件数据的中大小
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *fullPath = [baseDOCUMENTPATH stringByAppendingPathComponent:response.suggestedFilename];
        [[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
            success ? success(filePath, 200, @"下载成功") : nil;
        }else {
            [[NSFileManager defaultManager] removeItemAtURL:filePath error:nil];
            failure ? failure(nil, -2, @"下载失败") : nil;
        }
    }];
    [downloadTask resume];
    return downloadTask;
}

/** 便利构造器 */
+ (NSURLSessionDataTask *) requestHEAD:(NSString *)URLString
                            parameters:(id)parameters
                               success:(requestBlock)success
                               failure:(requestBlock)failure {
    return [[self httpClient] HEAD:URLString parameters:parameters success:success failure:failure];
}

// HEAD
- (NSURLSessionDataTask *)HEAD:(NSString *)URLString
                    parameters:(id)parameters
                       success:(requestBlock)success
                       failure:(requestBlock)failure
{
    return [_AFNHttpManager HEAD:URLString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task) {
        //有结果返回
        success ? success(nil, 200, @"请求成功") : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //网络请求失败
        failure ? failure(nil, error.code, @"网络请求失败") : nil;
        
    }];
}


//- (void)goLogin{
//    //退出设置为根视图
//    CLCWLoginVC *loginController = [[CLCWLoginVC alloc]init];
//    //退出设置为根视图
//    UIWindow *keyWindow = [[UIApplication sharedApplication]keyWindow];
//    keyWindow.rootViewController = nil;
//    keyWindow.rootViewController = [[CLCWNavigationVC alloc]initWithRootViewController: loginController];
//}

#pragma mark -- 上传图片 -- 盘点用到的上传方法
//上传单张
+ (void)uploadWithURLString:(NSString *)URLString
                 parameters:(id)parameters
                 uploadData:(NSData *)uploadData
                 uploadName:(NSString *)uploadName
                   fileName:(NSString *)fileName
                contentType:(NSString *)contentType
                    success:(requestBlock)success
                    failure:(requestBlock)failure
{
    return [[self httpClient] uploadWithURLString:URLString parameters:parameters uploadData:uploadData uploadName:uploadName fileName:fileName contentType:contentType success:success failure:failure];
}

// 上传文件
- (void)uploadWithURLString:(NSString *)URLString
                 parameters:(id)parameters
                 uploadData:(NSData *)uploadData
                 uploadName:(NSString *)uploadName
                   fileName:(NSString *)fileName
                contentType:(NSString *)contentType
                    success:(requestBlock)success
                    failure:(requestBlock)failure
{
    
    [_AFNHttpManager POST:URLString parameters:parameters constructingBodyWithBlock:^(id< AFMultipartFormData >  _Nonnull formData){
        [formData appendPartWithFileData:uploadData name:uploadName fileName:fileName mimeType:contentType];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
        //有数据返回
        success ? success(nil, 200, @"上传成功") : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        failure ? failure(nil, error.code, @"网络请求失败") : nil;
        
    }];
}



// 上传多张图片
+ (void)uploadMostImageWithURLString:(NSString *)URLString
                          parameters:(id)parameters
                         uploadDatas:(NSArray *)uploadDatas
                          uploadName:(NSString *)uploadName
                            fileName:(NSString *)fileName
                         contentType:(NSString *)contentType
                             success:(void (^)(id responseObject))success
                             failure:(void (^)(NSError *error))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id< AFMultipartFormData >  _Nonnull formData)
    {
        for (int i=0; i<uploadDatas.count; i++) {
            NSString *imageName = [NSString stringWithFormat:@"%@%d", uploadName, i+1];
            NSData *ImageData = UIImageJPEGRepresentation(uploadDatas[i], 0.5);
            [formData appendPartWithFileData:ImageData name:imageName fileName:fileName mimeType:contentType];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

//获取碎片 更新本地缓存库
+ (void) updateChipConfig
{
//    NSArray* chipArray=[[CLCWCachDataUtil getInstance] queryChipConfigArray];
//
//    NSMutableArray* paraArray=[[NSMutableArray alloc] init];
//
//    for (NameValueModel* item in chipArray) {
//        NSMutableDictionary* parametersDic=[[NSMutableDictionary alloc] init];
//        [parametersDic setValue: item.name forKey:@"name"];
//        [parametersDic setValue: item.valueData forKey:@"modify_time"];
//        [paraArray addObject:parametersDic];
//    }
//
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paraArray options:NSJSONWritingPrettyPrinted error:nil];
//    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    NSDictionary* parameters = @{@"config":jsonString};
//    [CLCWHttpClient requestPOST:CLCWCommonGetConfigUpdateURL parameters:parameters isNeedlogin:NO success:^(id data, long code, NSString *msgString) {
//        if (data) {
//            NSArray* dataArray=data;
//            for (NSDictionary* dic in dataArray) {
//                if ([CLCWCommonMethod isNull:dic]) {
//                    if (![dic[@"content"] isKindOfClass:[NSString class]]) {
//                        return ;//后台返回不是json字符串类型就return
//                    }
//                    [[CLCWCachDataUtil getInstance] updateChipConfig:[dic valueForKey:@"name"] content:[dic valueForKey:@"content"]  version:[[dic valueForKey:@"modify_time"] longLongValue]];
//                    if ([dic[@"name"] isEqualToString:@"auditing"]) {
//                        //增加审核环境测试
//                        NSString *auditVersionStr = [CLCWCommonMethod checkNull:dic[@"content"]];
//
//                        BOOL isAuditing = [auditVersionStr isEqualToString:[CLCWCommonMethod appVersionString]];
//
//                        //储存auditing状态
//                        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//                        [defaults setBool:isAuditing forKey:@"isAuditing"];
//                        [defaults synchronize];
//
//                        //根据储存状态恢复cookie
//                        [CLCWCommonMethod cookieSetupWithAuditing];
//                     }
//                }
//            }
//        }
//        //更新本地缓存库
//        [[CLCWCachDataUtil getInstance] updateLocalCachDB];
//    } failure:^(id data, long code, NSString *msgString) {
//        //更新本地缓存库
//        [[CLCWCachDataUtil getInstance] updateLocalCachDB];
//    }];
    
}



/*
+ (NSURLSessionDataTask *)requestWithNativeMethod:(HTTPMethod)method
                                              url:(NSString *)URLString
                                       parameters:(id)parameters
                                         progress:(void (^)(NSProgress * _Nonnull))uploadProgress
                                          success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                                          failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure {
    switch (method) {
        case POST:{
            return [[self getInstance].AFNHttpManager POST:URLString parameters:parameters progress:uploadProgress success:success failure:failure];
            break;
        }
        case GET:{
            return [[self getInstance].AFNHttpManager GET:URLString parameters:parameters progress:uploadProgress success:success failure:failure];
            break;
        }
    }
    
}
*/



@end
